/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
/**
 * Software License, Version 1.0
 *
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 *
 *
 *Redistribution and use in source and binary forms, with or without
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For
 * further information contact the Community Grids Lab at
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and
 * wherever such third-party acknowledgments normally appear.
 *
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering,
 * shall not be used to endorse or promote products derived from this software
 * without prior written permission from Indiana University.  For written
 * permission, please contact the Advanced Research and Technology Institute
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering,
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 *
 *
 * Indiana University provides no reassurances that the source code provided
 * does not infringe the patent or any other intellectual property rights of
 * any other entity.  Indiana University disclaims any liability to any
 * recipient for claims brought by any other entity based on infringement of
 * intellectual property rights or otherwise.
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS.
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS",
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION
 *GENERATED USING SOFTWARE.
 */

package cgl.narada.transport.udp;

import java.util.Enumeration;
import java.util.Hashtable;

/**
 * <p>
 * Title: UDPPackageCombine
 * </p>
 * <p>
 * Description: Helps to combine small packages which are the part of a bigger
 * package
 * </p>
 * 
 * @author Beytullah Yildiz
 * @version 1.0
 */

public class UDPPackageCombine extends Thread {

    private Hashtable ht;

    private Hashtable sizeht;

    private Hashtable timetolastupdate;

    String sunchpackhash = "synch1";

    String sunchsizehash = "synch2";

    boolean UDPCombine_Debug = false;

    private boolean keepLooping = true;

    private String moduleName = "UDPPackageCombine: ";

    /**
     * 
     * <p>
     * Title: TimeObject
     * </p>
     * <p>
     * Description: An internal class to handle package drop situation
     * </p>
     * 
     * @author Beytullah Yildiz
     * @version 1.0
     */
    class TimeObject {
        long key;

        long time;

        public TimeObject(long k, long t) {
            key = k;
            time = t;

        }

        public long getTime() {
            return time;
        }

        public long getKey() {
            return key;
        }
    }

    /**
     * Constructor
     */
    public UDPPackageCombine(boolean db) {
        UDPCombine_Debug = db;
        ht = new Hashtable();
        sizeht = new Hashtable();
        timetolastupdate = new Hashtable();
        setName("UDPPackageCombine");
    }

    public Hashtable getHT() {
        return ht;

    }

    public Hashtable getSizeHT() {
        return sizeht;
    }

    public void shutdownServices() {
        keepLooping = false;
        interrupt();
    }

    /**
     * combines small packages which is part of bigger package
     * 
     * @param pnumber
     *            unique number of big package
     * @param wholepacksize
     *            the whole size of big package
     * @param offset
     *            offset of small package in the big package
     * @param comingpackage
     *            the bytes of recevied small package
     * @return combined package
     */
    public byte[] recombinePack(long pnumber, int wholepacksize, int offset,
                                byte[] comingpackage) {
        byte[] returnbyte = null;
        int newsize;
        byte[] combinedarray = null;

        try {
            int comingpacksize = comingpackage.length;
            String spnumber = new Long(pnumber).toString();

            synchronized (sunchpackhash) {

                if (!ht.containsKey(spnumber)) {
                    byte[] wholepackage = new byte[wholepacksize];
                    ht.put(spnumber, wholepackage);
                    sizeht.put(spnumber, new Integer(0));

                }
            }

            combinedarray = (byte[]) ht.get(spnumber);
            System.arraycopy(comingpackage, 0, combinedarray, offset,
                             comingpacksize);

            synchronized (sunchsizehash) {

                newsize = ((Integer) sizeht.get(spnumber)).intValue()
                    + comingpacksize;
                sizeht.put(spnumber, new Integer(newsize));

                TimeObject timeobject = new TimeObject(pnumber, System
                    .currentTimeMillis());

                timetolastupdate.put(spnumber, timeobject);

            }

            if (newsize == wholepacksize) {
                // check if package completed if not, check time
                returnbyte = combinedarray;
                ht.remove(spnumber);
                sizeht.remove(spnumber);
                timetolastupdate.remove(spnumber);

            }

        } catch (Exception ex) {
            System.err.println("error in recomposing package");
            ex.printStackTrace();
        }

        return returnbyte;

    }

    /**
     * This suns a thread which drops a packages if they are not complited in a
     * given time
     */
    public void run() {
        while (keepLooping) {
            long currenttime = System.currentTimeMillis();
            Enumeration e = timetolastupdate.elements();
            while (e.hasMoreElements()) {

                TimeObject lg = (TimeObject) e.nextElement();
                long time = lg.getTime();
                if ((currenttime - time) > 2000) {
                    long key = lg.getKey();
                    String key_ = new Long(key).toString();

                    ht.remove(key_);
                    sizeht.remove(key_);
                    timetolastupdate.remove(key_);
                    if (UDPCombine_Debug) {
                        System.out
                            .println("The package dropped since it hasn't been completed");
                    }

                }
            }

            try {
                sleep(250);
            } catch (InterruptedException ex) {
                if (keepLooping) {
                    System.out.println(moduleName + "Problems sleeping ...");
                }
            }
        }
        if (UDPCombine_Debug) {
            System.out.println(moduleName + "Shutting down ...");
        }
    }

    public static void main(String[] args) {
    }

}